#!/usr/bin/python
import urllib
import simplejson  

class PyGoogleSearchAPI:                  
	"""This class is a Python wrapper to the Google search API. 
http://code.google.com/apis/ajaxsearch/documentation/reference.html#_class_GwebSearch
Text from the Google Web page: The API exposes a simple RESTful interface. In all cases, the method supported is GET and the response format is a JSON encoded result set with embedded status codes. Applications that use this interface must abide by all existing terms of use. An area to pay special attention to relates to correctly identifying yourself in your requests. Applications MUST always include a valid and accurate http referer header in their requests. In addition, we ask, but do not require, that each request contains a valid API Key. By providing a key, your application provides us with a secondary identification mechanism that is useful should we need to contact you in order to correct any problems. Read more about the usefulness of having an API key
	Like the core Javascript interface, this interface is exposed through a uniform URL containing a mix of both standard and searcher specific CGI arguments. Your application can use an http stack of it's choosing. The only requirements are that you must be able to construct a properly constructed URL with all necessary CGI arguments, that you send an http referer header that accurately identifies your application, and that you are able to process the JSON encoded response.""" 
	
	__web_search_url	 = 'http://ajax.googleapis.com/ajax/services/search/web?'     
	__local_search_url = 'http://ajax.googleapis.com/ajax/services/search/local?'
	__video_search_url = 'http://ajax.googleapis.com/ajax/services/search/video?'
	__blog_search_url  = 'http://ajax.googleapis.com/ajax/services/search/blogs?'
	__news_search_url	 = 'http://ajax.googleapis.com/ajax/services/search/news?'
	__book_search_url  = 'http://ajax.googleapis.com/ajax/services/search/books?'
	__image_search_url = 'http://ajax.googleapis.com/ajax/services/search/images?'
	__patent_search_url= 'http://ajax.googleapis.com/ajax/services/search/patent?'    
	
	__searcher_name = ''  
	__url = ''
	data = {	
		'v'		: '1.0',      
		'start'	: 0,
		'q'     : '',
		'rsz'   : 'small', 
		'key'	: '', 
		'start' : ''		
	  }
	 
	def __init__(self, searcher='web_search', key=None, version=1.0):	  
		self.set_searcher(searcher)    
		self.__add_float_param('v', version)  
		
		if key is not None: 
			self.__add_string_param('key', key)			                           
	    
	def __add_string_param(self, key, param): 
		self.data[key] = param
			
	def __add_int_param(self, key, param): 
 		self.data[key] = '%d' % param    
		
	def __add_float_param(self, key, param):
		 self.data[key] = '%0.1f' % param
	 	  	
	def set_searcher(self, searcher='web_search'):
		(self.__searcher_name, self.__url) = {
			'web_search'	: ('web_search', self.__web_search_url),
			'local_search'	: ('local_search', self.__local_search_url)
		}[searcher]	       
		
	def __search_times(self, hits):  
		if self.data['rsz'] == 'small':
			if hits%4 == 0:
				return ( hits / 4 )
			else:
				return ( hits / 4 ) +1 
		if self.data['rsz'] == 'large':
			 if hits%8 == 0:
			 	return ( hits / 8 )
			 else:
				return ( hits / 8 ) + 1
		else:         
			return 1; 
		
	def search(self, query, hits=4, start=0): 
		"""TODO: {"responseData": null, "responseDetails": "invalid key", "responseStatus": 400}"""                         		
		counter = 0 
		value = 4
	 	if self.data['large'] == 'small': 
			value = 8 
		   
		self.__add_string_param('q', urllib.urlencode({'q':query}).split('=')[1])  
		for i in range(self.__search_times(hits)):
			self.__add_int_param('start', start+counter)
			search_url = self.__url+'&'.join(['%s=%s' % (k,v) for k,v in self.data.items() if v is not ''])
			counter += value
			search_results = urllib.urlopen(search_url)			
			json = simplejson.loads(search_results.read())  
			search_results.close()
			results = json['responseData']['results']			
			if(counter > hits): 
				left = value-(counter-hits) 		 
				results = results[:left]			
			print '\n'.join(['%s' % i['url'] for i in results])
			   